package cn.funeralobjects.common.web.controller;

import cn.funeralobjects.common.service.EntityService;
import cn.funeralobjects.util.ReactorUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import reactor.core.publisher.Mono;

/**
 * 基础的带有模型的Controller
 *
 * @author FuneralObjects
 * Create date: 2020/4/27 5:44 PM
 */
public interface RestEntityController<VO, Entity, ID> extends ModelMapperController<Entity, VO>, IdController<ID> {

    /**
     * 实体业务
     *
     * @return EntityService
     */
    EntityService<Entity, ID> entityService();

    /**
     * 获取数据
     *
     * @param id id
     * @return 实体数据
     */
    @GetMapping("/{id}")
    default Mono<VO> findById(@PathVariable ID id) {
        return Mono.just(id)
                .filter(this::isValid)
                .map(entityService()::findById)
                .map(this::toVo)
                .flatMap(ReactorUtils::getOrEmpty);
    }

    /**
     * 删除数据
     *
     * @param id id
     * @return 无返回
     */
    @DeleteMapping("/{id}")
    default Mono<Void> deleteById(@PathVariable ID id) {
        return Mono.just(id)
                .filter(this::isValid)
                .flatMap(ReactorUtils.thenEmpty(entityService()::deleteById));
    }

    /**
     * 分页查询数据
     *
     * @param num  页码
     * @param size 条数
     * @return 分页数据
     */
    @GetMapping("/page/{num}-{size}")
    default Mono<Page<VO>> findPage(@PathVariable Integer num, @PathVariable Integer size) {
        return Mono.just(PageRequest.of(num, size))
                .map(entityService()::findAll)
                .map(p -> p.map(this::toVo));
    }

}
